<template>
  <div class="check-form-container">
    <el-card class="check-form-card" shadow="hover">
      <div slot="header" class="card-header">
        <span>{{ $t('attendance.leave') }}</span>
      </div>
      <el-form 
        ref="form" 
        :model="form" 
        :rules="rules" 
        label-width="100px" 
        :class="{'mobile-form': isMobile}"
        size="medium">
        <el-form-item :label="$t('attendance.leaveType')" prop="leaveTypeId">
          <el-select v-model="form.leaveTypeId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.leaveType')" style="width: 100%;">
            <el-option 
              v-for="type in leaveTypes" 
              :key="type.id" 
              :label="getLeaveTypeLabel(type)" 
              :value="type.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('course.title')" prop="courseId">
          <el-select v-model="form.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" style="width: 100%;" @change="handleCourseChange">
            <el-option 
              v-for="course in courses" 
              :key="course.id" 
              :label="course.name" 
              :value="course.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('attendance.leaveTime')" prop="leaveDate">
          <el-date-picker
            v-model="form.leaveDate"
            type="datetime"
            :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.leaveTime')"
            style="width: 100%;"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item :label="$t('attendance.leaveReason')" prop="reason">
          <el-input 
            type="textarea" 
            v-model="form.reason" 
            :placeholder="$t('attendance.leaveReasonPlaceholder')"
            :rows="4">
          </el-input>
        </el-form-item>
        
        <el-form-item class="form-buttons">
          <el-button type="primary" @click="submitForm('form')" :loading="submitting" round>{{ $t('attendance.submitLeave') }}</el-button>
          <el-button @click="resetForm('form')" :disabled="submitting" round>{{ $t('common.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import ElementUI from "element-ui";

export default {
  name: "LeaveStudent",
  data() {
    return {
      submitting: false,
      isMobile: window.innerWidth <= 768,
      courses: [],
      leaveTypes: [],
      form: {
        leaveTypeId: '',
        leaveDate: '',
        reason: '',
        courseId: '',
        userId: '',
        groupId: ''
      },
      rules: {
        leaveTypeId: [
          { required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('attendance.leaveType'), trigger: 'change' }
        ],
        courseId: [
          { required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('course.title'), trigger: 'change' }
        ],
        leaveDate: [
          { required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('attendance.leaveTime'), trigger: 'change' }
        ],
        reason: [
          { required: true, message: this.$t('common.pleaseEnter') + ' ' + this.$t('attendance.leaveReason'), trigger: 'blur' },
          { min: 5, max: 200, message: this.$t('common.lengthLimit', {min: 5, max: 200}), trigger: 'blur' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 不能选择过去的日期
        }
      }
    }
  },
  created() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
    // 获取用户已选课程列表
    this.getUserCourses();
    // 获取请假类型列表
    this.getLeaveTypes();
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 处理窗口大小变化
    handleResize() {
      this.isMobile = window.innerWidth <= 768;
    },
    
    // 获取请假类型列表
    getLeaveTypes() {
      this.$axios.get("/leave/types").then(res => {
        if (res.code === 200) {
          this.leaveTypes = res.data || [];
        } else {
          this.$message.error(res.data.msg || this.$t('attendance.checkAdmin.getCourseFailed'));
        }
      }).catch(() => {
        this.$message.error(this.$t('common.operationFailedRetry'));
      });
    },
    
    // 获取用户已选课程列表
    getUserCourses() {
      const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      if (!userInfo || !userInfo.userId) {
        this.$message.error(this.$t('user.loginRequired'));
        return;
      }
      
      this.$axios.get(`/course/student/${userInfo.userId}`).then(res => {
        if (res.code === 200) {
          this.courses = res.data || [];
        } else {
          this.$message.error(res.data.msg || this.$t('course.getCoursesError'));
        }
      }).catch(() => {
        this.$message.error(this.$t('common.operationFailedRetry'));
      });
    },
    
    // 处理课程选择变化
    handleCourseChange(courseId) {
      const course = this.courses.find(c => c.id === courseId);
      if (course) {
        this.form.groupId = course.groupId;
      }
    },
    
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.onSubmit();
        }
      });
    },
    
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    
    // 提交请假申请
    onSubmit() {
      this.submitting = true;
      
      // 设置用户ID
      const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      this.form.userId = userInfo.userId;
      
      // 创建提交数据
      const submitData = {
        userId: this.form.userId,
        courseId: this.form.courseId,
        groupId: this.form.groupId,
        leaveTypeId: this.form.leaveTypeId,
        leaveDate: this.formatToISOString(this.form.leaveDate),
        reason: this.form.reason
      };
      
      this.$axios.post("/leave/submit", submitData).then(res => {
        this.submitting = false;
        if (res.code === 200) {
          this.$message.success(this.$t('common.operationSuccess'));
          this.resetForm('form');
        } else {
          this.$message.error(res.data.msg || this.$t('common.operationFailed'));
        }
      }).catch(() => {
        this.submitting = false;
        this.$message.error(this.$t('common.operationFailedRetry'));
      });
    },
    
    // 将日期转换为ISO格式
    formatToISOString(dateStr) {
      if (!dateStr) return '';
      // 如果已经是Date对象，直接使用；否则创建Date对象
      const date = dateStr instanceof Date ? dateStr : new Date(dateStr);
      return date.toISOString();
    },
    
    // 获取请假类型标签
    getLeaveTypeLabel(type) {
      if (!type) return this.$t('common.unknown');
      
      // 对常见的请假类型进行国际化转换
      const typeTranslateMap = {
        '病假': 'attendance.checkAdmin.sickLeave',
        '事假': 'attendance.checkAdmin.personalLeave'
      };
      
      // 如果是预设的请假类型，则使用国际化翻译
      if (typeTranslateMap[type.name]) {
        return this.$t(typeTranslateMap[type.name]);
      }
      
      // 对于其他未预设的请假类型，直接返回原始名称
      return type.name;
    }
  }
}
</script>

<style scoped>
.check-form-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.check-form-card {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  transition: all 0.3s;
  border-radius: 8px;
}

.check-form-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.form-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 移动端适配 */
.mobile-form .el-form-item__label {
  float: none;
  display: block;
  text-align: left;
  padding: 0 0 10px;
}

.mobile-form .el-form-item__content {
  margin-left: 0 !important;
}

/* 日期选择器在移动端的样式 */
.date-picker-mobile {
  width: 100% !important;
}

@media screen and (max-width: 768px) {
  .check-form-container {
    padding: 10px;
  }
  
  .check-form-card {
    border-radius: 4px;
  }
  
  .form-buttons {
    flex-direction: column;
    gap: 10px;
  }
  
  .form-buttons .el-button {
    width: 100%;
  }
}
</style>